package com.fable.web.controller.workdaily;

import com.alibaba.fastjson.JSON;
import com.fable.base.PaginationResult;
import com.fable.biz.operate.AdminUserService;
import com.fable.biz.operate.CreateWorkdailyModel;
import com.fable.biz.operate.WorkDailyService;
import com.fable.biz.operate.query.WorkDailyQueryCondition;
import com.fable.common.config.RequireLogin;
import com.fable.common.constant.FableConstant;
import com.fable.common.utils.JsonResult;
import com.fable.dal.dto.AdminUserDTO;
import com.fable.dal.model.AdminUserDO;
import com.fable.dal.model.WorkDailyDO;
import com.fable.utils.CalendarUtil;
import com.fable.utils.StringUtil;
import com.fable.web.common.annotation.Track;
import com.fable.web.controller.base.BaseController;
import com.fable.web.page.P;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * Created by weishuai on 18/4/7.
 */
@RequireLogin
@Controller
@RequestMapping("/workdaily")
public class WorkDailyController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WorkDailyService workDailyService;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    protected HttpServletResponse response;

    @RequestMapping("/workdailyList.htm")
    @Track(tag = P.UrlEnum.workdailyList)
    public String list(HttpServletRequest request, ModelMap model, WorkDailyQueryCondition condition) {
        AdminUserDTO adminDO = (AdminUserDTO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
        if (adminDO != null && !"boss".equals(adminDO.getRoleName())) {
            condition.setUserId(adminDO.getId());
        }
        if (StringUtil.isBlank(condition.getDate())) {
            Date currentDate = new Date();
            if (StringUtil.isBlank(condition.getStartTime())) {
                String date = CalendarUtil.toString(currentDate, CalendarUtil.DATE_FMT_3);
                condition.setStartTime(date);
            }
            if (StringUtil.isBlank(condition.getEndTime())) {
                String date = CalendarUtil.toString(currentDate, CalendarUtil.DATE_FMT_3);
                condition.setEndTime(date);
                condition.setDate(date);
            }
        }
        PaginationResult<WorkDailyDO> result = workDailyService.searchWorkDaily(condition);
        List<AdminUserDTO> userDOList = adminUserService.findUser(null);
        List<WorkDailyDO> workDailyDOList = result.getResultList();

        if("boss".equals(adminDO.getRoleName())){
            StringBuffer info = new StringBuffer();
            for (AdminUserDTO userDO : userDOList) {
                if ("boss".equals(userDO.getRoleId())) {
                    continue;
                }
                int userId = userDO.getId();
                boolean isCommit = false;
                if(!CollectionUtils.isEmpty(workDailyDOList)){
                    for (WorkDailyDO workDailyDO : workDailyDOList) {
                        if (userId == workDailyDO.getUserId()) {
                            isCommit = true;
                            continue;
                        }
                    }
                }
                //未检索出提交情况
                if (!isCommit) {
                    info.append(userDO.getNick() + ",");
                }
            }

            model.put("info", info);
        }
        model.put("paginationResult", result);
        model.put("query", condition);
        return "workdaily/workdailyList";
    }


    @RequestMapping("/addWorkdaily.htm")
    @Track(tag = P.UrlEnum.addWorkdaily)
    public String add(ModelMap model) {
        Date currentDate = new Date();
        String date = CalendarUtil.toString(currentDate, CalendarUtil.DATE_FMT_3);
        model.put("date", date);
        return "workdaily/addWorkdaily";
    }

    @RequestMapping("/editWorkdaily.htm")
    @Track(tag = P.UrlEnum.editWorkdaily)
    public String edit(ModelMap model, Long id) {
        Date currentDate = new Date();
        String date = CalendarUtil.toString(currentDate, CalendarUtil.DATE_FMT_3);
        model.put("date", date);
        if (id != null) {
            WorkDailyDO workDailyDO = workDailyService.getById(id);
            model.put("result", workDailyDO);
        }
        return "workdaily/editWorkdaily";
    }

    @RequestMapping("/saveWorkdaily.htm")
    @Track(tag = P.UrlEnum.saveWorkdaily)
    public String saveCustomer(ModelMap model, HttpServletRequest request, CreateWorkdailyModel workdailyModel) {
        if (StringUtil.isBlank(workdailyModel.getContent())) {
            return "workdaily/addWorkdaily";
        }
        AdminUserDO adminDO = (AdminUserDO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
        if (adminDO == null) {
            return P.Common.login;
        }
        WorkDailyDO workDailyDO = new WorkDailyDO();
        model.put("result", workDailyDO);
        try {
            if (workDailyDO.getId() != null) {
                workDailyDO = workDailyService.getById(workDailyDO.getId());
                workDailyDO.setGmtModified(new Date());
                BeanUtils.copyProperties(workdailyModel, workDailyDO);
                workDailyService.update(workDailyDO);
            } else {
                BeanUtils.copyProperties(workdailyModel, workDailyDO);
                Date date = new Date();
                workDailyDO.setGmtCreate(date);
                workDailyDO.setGmtCreate(date);
                workDailyService.add(workDailyDO);
            }
        } catch (Exception e) {
            logger.error("保存日报,param:{}", JSON.toJSONString(workDailyDO), e);
            model.put("msg", "保存异常请联系管理员!");
            return "workdaily/addWorkdaily";
        }
        return P.redirectPrex("/workdaily/workdailyList");
    }


    @RequestMapping("/editWorkdaily.json")
    @Track(tag = P.UrlEnum.editWorkdaily)
    @ResponseBody
    public JsonResult editCustomer(HttpServletRequest request, @ModelAttribute CreateWorkdailyModel workdailyModel) {
        JsonResult jsonResult = new JsonResult();

        AdminUserDO adminDO = (AdminUserDO) request.getSession().getAttribute(FableConstant.USER_SESSION_KEY);
        if (adminDO == null) {
            jsonResult.setCustomErrCode("-1", "未登录");
            return jsonResult;
        }
        Date date = new Date();
        String myDate = CalendarUtil.toString(date, CalendarUtil.DATE_FMT_3);
        workdailyModel.setDate(myDate);
        workdailyModel.setUserId(adminDO.getId());
        workdailyModel.setUserName(adminDO.getNick());
        WorkDailyDO workDailyDO = new WorkDailyDO();
        try {
            if (workdailyModel.getId() != null) {
                workDailyDO = workDailyService.getById(workdailyModel.getId());
                workDailyDO.setGmtModified(new Date());
                BeanUtils.copyProperties(workdailyModel, workDailyDO);
                workDailyService.update(workDailyDO);
            } else {
                WorkDailyQueryCondition condition = new WorkDailyQueryCondition();
                condition.setUserId(adminDO.getId());
                condition.setStartTime(myDate);
                condition.setEndTime(myDate);
                PaginationResult<WorkDailyDO> paginationResult = workDailyService.searchWorkDaily(condition);
                if (paginationResult != null && !CollectionUtils.isEmpty(paginationResult.getResultList())) {
                    logger.warn("当天日报已经写过,请勿重复写,userId:{},param:{}", JSON.toJSONString(adminDO), JSON.toJSONString(workdailyModel));
                    jsonResult.setCustomErrCode("0", "当天日报已存在,请勿重复提交!");
                    return jsonResult;
                }

                BeanUtils.copyProperties(workdailyModel, workDailyDO);
                workDailyDO.setGmtCreate(date);
                workDailyDO.setGmtCreate(date);
                workDailyDO.setDate(myDate);
                workDailyService.add(workDailyDO);
            }
        } catch (Exception e) {
            logger.error("保存日报异常,param:{}", JSON.toJSONString(workdailyModel), e);
            jsonResult.setErrMsg("保存异常请联系管理员!");
            return jsonResult;
        }
        return jsonResult;
    }


}
